package com.gorhaf.coder.mvc.ws;

import jakarta.websocket.*;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.stereotype.Component;

import java.util.HashSet;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint("/websocket/{userId}")
@Component
public class GameEndpoint {

    private static ConcurrentHashMap<String, GameEndpoint> chats = new ConcurrentHashMap<>();
    private static int count = 0;

    private Session session;
    private String userId;

    /**
     * 参数有两种形式：
     * 1.String message, Session session
     * 2.byte[] b, boolean last, Session session
     *
     * @param message 消息
     * @param session 会话
     */
    @OnMessage
    public void onMessage(String message, Session session) {
        System.out.println("收到的消息：" + message);
        session.getAsyncRemote().sendText(message);
    }

    @OnOpen
    public void onOpen(Session session, @PathParam("userId") String userId, EndpointConfig config) {
        this.session = session;
        this.userId = userId;
        chats.put(userId, this);
        count++;
        // 同步
        /*RemoteEndpoint.Basic basicRemote = session.getBasicRemote();
        try {
            basicRemote.sendText("hi");
        } catch (IOException e) {
            System.out.println(e);
        }*/
        // 异步
        /*RemoteEndpoint.Async asyncRemote = session.getAsyncRemote();
        asyncRemote.sendText("hello");*/
    }

    @OnClose
    public void onClose(Session session, CloseReason closeReason) {
        System.out.println("onClose");
        chats.remove(userId);
        count--;
    }

    @OnError
    public void onError(Session session, Throwable thr) {
        System.out.println("onError");
    }

    /**
     * 发送消息
     *
     * @param message 消息
     */
    public void sendMessage(String message) {
        session.getAsyncRemote().sendText(message);
    }

    /**
     * 根据用户ID发送消息
     *
     * @param message 消息
     */
    public void sendMessage(String userId, String message) {
        chats.get(userId).sendMessage(message);
    }
}
